import $bus from '../model/bus'
import getScript from '../util/getScript'

// 确保 user 组件只被加载一次
let cacheUser = null
let cachePm = null
export function getUserApi () {
	if (!cachePm) {
		cachePm = new Promise(resolve => {
			if (cacheUser) {
				resolve(cacheUser)
			} else {
				getScript({
					src: '//s.yangshipin.cn/CCTVVideo/CCTVVideoH5Account/cctvh5-account.min.js',
					charset: 'utf-8',
					onLoad() {
						cacheUser = window['cctvh5-account'].default
						resolve(cacheUser)
					}
				})
			}
		})
	}
	return cachePm
}

// 封装用户信息获取与登录逻辑
const User = {}

const methods = [
	'info',
	'isSigned',
	'signin',
	'signout'
]

methods.forEach(name => {
	User[name] = async function() {
		let $user = await getUserApi()
		let rs = null
		if (typeof $user[name] === 'function') {
			rs = await $user[name]()
		}
		return rs
	}
})

// 登录
$bus.on('require-signin', () => {
	User.signin()
})

export default User
